package com.wangl.spring.utils;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.search.FileTypeIndex;
import com.intellij.psi.search.GlobalSearchScope;
import com.wangl.spring.suggestion.filetype.SpringConfigurationYamlFileType;
import org.jetbrains.yaml.YAMLUtil;
import org.jetbrains.yaml.psi.YAMLFile;
import org.jetbrains.yaml.psi.YAMLKeyValue;

import java.util.*;

/**
 * @ClassName YamlFileUtil
 * @Description TODO
 * @Author wangl
 * @Date 2023/8/7 16:49
 */
public class YamlFileUtil {

    public static Set<PsiElement> findByKey(String placeholder, GlobalSearchScope scope, Project project){
        Collection<VirtualFile> yamlFiles = FileTypeIndex.getFiles(SpringConfigurationYamlFileType.INSTANCE, scope);
        Set<PsiElement> result = new HashSet<>();
        for (VirtualFile yamlVirtualFile : yamlFiles) {
            PsiManager psiManager = PsiManager.getInstance(project);
            PsiFile psiFile = psiManager.findFile(yamlVirtualFile);
            YAMLFile yamlFile = (YAMLFile) psiFile;
            if (Objects.isNull(yamlFile)){
                continue;
            }
            String[] keys = placeholder.split("\\.");
            YAMLKeyValue yamlKeyValue = YAMLUtil.getQualifiedKeyInFile(yamlFile, keys);
            if (Objects.nonNull(yamlKeyValue)){
                result.add(yamlKeyValue);
            }
        }
        return result;
    }
}
